package com.gcsj.gcsjspringboot.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gcsj.gcsjspringboot.common.utils.Constant;
import com.gcsj.gcsjspringboot.common.utils.PageUtils;
import com.gcsj.gcsjspringboot.common.utils.Query;
import com.gcsj.gcsjspringboot.dao.WorkRecordDao;
import com.gcsj.gcsjspringboot.entity.SysUserEntity;
import com.gcsj.gcsjspringboot.entity.WorkRecordEntity;
import com.gcsj.gcsjspringboot.service.SysUserService;
import com.gcsj.gcsjspringboot.service.WorkRecordService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;


@Service("workRecordService")
public class WorkRecordServiceImpl extends ServiceImpl<WorkRecordDao, WorkRecordEntity> implements WorkRecordService {
    @Autowired
    SysUserService userService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        String name = (String) params.get("name");
        Long userId = (Long) params.get("userId");
        String workDate = (String) params.get("workDate");

        List<SysUserEntity> users = userService.list(new QueryWrapper<SysUserEntity>()
                .like("name", name));

        List<Long> ids = new ArrayList<>();
        for (SysUserEntity user : users) {
            ids.add(user.getUserId());
        }
        IPage<WorkRecordEntity> page = null;
        if(userId == 1){
            // 管理员
            page = this.page(
                    new Query<WorkRecordEntity>().getPage(params),
                    new QueryWrapper<WorkRecordEntity>()
                            .in(StringUtils.isNotBlank(name), "user_id", ids)
                            .eq(StringUtils.isNotBlank(workDate), "work_date", workDate)
            );
        } else {
            page = this.page(
                    new Query<WorkRecordEntity>().getPage(params),
                    new QueryWrapper<WorkRecordEntity>()
                            .in(StringUtils.isNotBlank(name), "user_id", ids)
                            .eq(StringUtils.isNotBlank(workDate), "work_date", workDate)
                            .eq("user_id", userId)
            );
        }

        return new PageUtils(page);
    }

}
